/*****目标团队*****/
<template
  ><!---->
  <SearchTable
    :columns="targetTeamCol" 
    :data="targetTeamData"
    :total="targetTeamTotal"
    :page.sync="queryTargetTeamInfo.pageIndex"
    :size.sync="queryTargetTeamInfo.pageSize"
    @queryFun="getTargetTeamList">
    <template slot="search">
      <!--<Input v-model.trim="queryTargetTeamInfo.name"  placeholder="题目显示名称" style="width: 200px" @on-search="searchTargetTeam"  />
      <Input v-model.trim="queryTargetTeamInfo.teamName"  placeholder="团队名称" style="width: 200px" @on-search="searchTargetTeam"  />
      <Select filterable v-model="queryTargetTeamInfo.status" placeholder="请选择状态"  style="width: 200px" @on-change="searchTargetTeam" clearable> 
           <Option :value="1" v-if="type == 4">未攻破</Option>
           <Option :value="1" v-else>正常/防护成功</Option>
           <Option :value="2">已攻破</Option>
           <Option :value="3">服务异常</Option>
           <Option :value="4">已攻破+服务异常</Option>
      </Select>-->
    </template>
  </SearchTable>
</template>

<script>
import {
  getTargetTeamList,
  addTargetTeam,
  modifyTargetTeam,
  getTargetTeamInfo,
  topoTargetStatis,
  topoAtTargetStatis,
  topoDeTargetStatis
} from '@/api/drill_compete';
import { queryCtfList } from '@/api/question';
import { getaccessgrouplist } from '@/api/access_new';
export default {
  name: 'scenes',
  props: ['type', 'poll', 'isDefend','hwType'], //接受演练竞赛类型
  components: {  },
  data() {
    return {
      routeParams: {
        id: this.$route.query.id,
        prjid: this.$route.query.prjid
      },
      targetModal: {
        show: false,
        title: '',
        loading: true,
        type: 1 //1添加，2修改
      },
      accessGroupList: [],
      vmlists: [],
      teamlists: [],
      testId: this.$route.query.id,
      queryTargetTeamInfo: {
        pageIndex: 1,
        pageSize: 10
      },
      questionList: [],
      formValidate: {
        //"createTime": "2020-02-10T03:35:50.081Z",
        //"creator": "string",
        description: '', //目标描述
        externalIp: '', //对外ip
        externalPort: 1, //对外端口
        //"ip": "string",
        name: '', //目标名称
        //"password": "string",
        //"port": "string",
        projectId: this.$route.query.prjid,
        questionId: '', //题目id
        sceneId: this.$route.query.id,
        score: 0,
        //"status": 0, //状态：1 正常/防护成功，2 被攻破，3 服务异常，4 被攻破+服务异常
        teamId: '',
        teamName: '',
        type: 0, //目标类型：0.单个虚拟机、1.多个虚拟机flag相同、2.多个虚拟机flag不同、3.文件类型
        //"user": "string",
        visibility: 0, //可见性：是否可见- 0.不可见 1可见
        vmId: ''
      },
      ruleValidate: {
        name: [{ required: true, message: '名字不能为空', trigger: 'change' }],
        description: [{ required: true, message: '请输入描述信息', trigger: 'change' }],
        type: [{ required: true, type: 'number', message: '请选择靶标类型', trigger: 'change' }],
        score: [{ required: true, type: 'number', message: '请输入分值', trigger: 'change' }],
        externalIp: [{ required: true, message: '请输入对外IP', trigger: 'change' }],
        externalPort: [
          { required: true, type: 'number', message: '请输入对外端口', trigger: 'change' }
        ],
        //        questionId:[
        //        	{ required: true, message: '请选择题目', trigger: 'change'}
        //        ],
        visibility: [{ required: true, type: 'number', message: '请选择', trigger: 'change' }],
        vmId: [{ required: true, message: '请选择虚拟机', trigger: 'change' }],
        teamId: [{ required: true, message: '请选择团队', trigger: 'change' }]
      },
      initTargetObjData: {
        createtime: '',
        createuser: localStorage.getItem('username'),
        frequency: 0,
        id: '',
        isshow: 1,
        lastupdatetime: '',
        modifier: '',
        sceneid: '',
        targetdes: '',
        targetname: '',
        targetsubmittype: 0,
        targettype: 0,
        teamid: '',
        type: 0,
        uri: '',
        vmid: '',
        score: '0'
      },
      querytime: {},
      categoryObj: {
        '1': {
          label: '一类',
          value: '1'
        },
        '2': {
          label: '二类',
          value: '2'
        },
        '3': {
          label: '三类',
          value: '3'
        }
      },
      targetTeamCol: [
        {
          title: '目标名称',
          key: 'name',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 240,
          placement: 'top-left',
          order: 1
        },
        {
          title: '单位',
          show: () => {
            return this.isDefend;
          },
          key: 'company',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 120,
          placement: 'top-left'
        },
        {
          title: '类别',
          key: 'category',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          placement: 'top-left',
          render: (h, { row: { category } }) => {
            return h('span', category ? this.categoryObj[category].label : '无');
          },
          // show:this.hwType !== 3
        },
        {
          title: '提交总次数',
          key: 'allTotal',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 60
        },
        {
          title: '未审核数',
          key: 'noFinishTotal',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 60
        },
        {
          title: '审核通过数',
          key: 'finishTotal',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 60
        },
        {
          title: '审核未通过数',
          key: 'turnTotal',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 60
        },
        {
          title: '挂起数',
          key: 'hangTotal',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 60
        },
        {
          title: '驳回再提交数',
          key: 'rejectTotal',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 60
        }
      ],
      targetTeamData: [],
      targetTeamTotal: 0,
      TargetId: '',
      timeout: {}
    };
  },
  filters: {},
  watch: {},
  beforeDestroy () {
    console.log('========');
    clearInterval(this.timeout);
  },
  mounted() {
    //this.getAllSence()
    //this.getAllTargetHost();
    //this.getAllVmlist();

    //this.getAccessGroupList();
    //this.queryCtfQuestionList();

    this.getTargetTeamList();
  },
  methods: {
    showAddAndUpdate(info) {
      this.targetModal.show = true;
      if (!info) {
        this.targetModal.title = '添加题目';
        this.targetModal.type = 1;
      } else {
        this.targetModal.title = '修改题目';
        this.targetModal.type = 2;
        this.formValidate = {};
        this.formValidate = JSON.parse(JSON.stringify(info));
        this.question = { imageId: this.formValidate.imageId };
        this.setTeamGroup(this.formValidate.teamId);
        this.formValidate.externalPort = parseInt(this.formValidate.externalPort);
      }
    },
    addTargetTeam() {
      addTargetTeam(this.formValidate)
        .then((data) => {
          if (data.code == 1) {
            this.getTargetTeamList();
            this.$Message.info('操作成功');
            this.handleReset('formValidate');
            this.targetModal.show = false;
          } else {
            this.cancelLoading('targetModal');
          }
        })
        .catch((error) => {
          this.cancelLoading('targetModal');
        });
    },
    modifyTargetTeam() {
      modifyTargetTeam(this.formValidate)
        .then((data) => {
          if (data.code == 1) {
            this.getTargetTeamList();
            this.$Message.info('操作成功');
            this.handleReset('formValidate');
            this.targetModal.show = false;
          } else {
            this.cancelLoading('targetModal');
          }
        })
        .catch((error) => {
          this.cancelLoading('targetModal');
        });
    },
    saveTargetTeam() {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          if (this.targetModal.type == 1) {
            this.addTargetTeam();
          } else {
            this.modifyTargetTeam();
          }
        } else {
          this.cancelLoading('targetModal');
        }
      });
    },
    getTargetTeamList() {
      this.timeout && clearInterval(this.timeout);
      let resApi = this.isDefend ? topoDeTargetStatis : topoAtTargetStatis;
      resApi(this.testId, this.queryTargetTeamInfo).then((data) => {
        if (data.code == 1) {
          this.targetTeamData = data.data.items;
          this.targetTeamTotal = data.data.total;
          if (this.poll) {
            //如果需要轮询
            this.timeout = setInterval(() => {
              console.log('====进入定时器');
              this.getTargetTeamList();
            }, 3000);
          }
        } else {
        }
      });
    },
    changePage(page) {
      this.queryTargetTeamInfo.page = page;
      this.getTargetTeamList();
    },
    delTargetTeam(id) {
      delTargetTeam(id).then((data) => {
        if (data.code == 1) {
          this.getTargetTeamList();
        } else {
        }
      });
    },
    cancelLoading(name) {
      this[name].loading = false;
      setTimeout(() => {
        this[name].loading = true;
      });
    },
    stStatusFilter(val) {
      let str = '';
      switch (val) {
        case 1:
          str = '未攻破';
          break;
        case 2:
          str = '被攻破';
          break;
        case 3:
          str = '服务异常';
          break;
        case 4:
          str = '被攻破+服务异常';
          break;
        default:
          break;
      }
      return str;
    },
    statusFilter(val, type) {
      let str = '';
      if (type == 'text') {
        switch (val) {
          case 1:
            str = '正常/防护成功';
            break;
          case 2:
            str = '被攻破';
            break;
          case 3:
            str = '服务异常';
            break;
          case 4:
            str = '被攻破+服务异常';
            break;
          default:
            break;
        }
      } else {
        switch (val) {
          case 1:
            str = 'success';
            break;
          case 2:
            str = 'warning';
            break;
          case 3:
            str = 'warning';
            break;
          case 4:
            str = 'error';
            break;
          default:
            break;
        }
      }
      return str;
    },
    getAllVmlist(partyId, imageId) {
      let params = {
        page: 1,
        pageSize: 10000,
        sortBy: 'name',
        order: 'asc'
      };
      if (this.question) {
        params.imageId = this.question.imageId;
      }
      if (this.group) {
        params.party = this.group.partyId;
      }
      queryVmWithParty(this.routeParams.prjid, params).then((data) => {
        if (data.code == 1) {
          this.vmlists = data.data.list || data.data;
        }
      });
    },
    getAccessGroupList() {
      if (!this.routeParams.id) {
        return;
      }
      let params = {
        pageIndex: 1,
        pageSize: 2147483647,
        testId: this.routeParams.id
      };
      this.selectGroupList = [];
      //			this.getPartyList();
      getaccessgrouplist(params).then((data) => {
        if (data.code == 1) {
          this.accessGroupList = data.data.items;
        } else if (data.code == -2) {
          this.accessGroupList = [];
        } else {
          this.$Message.warning(data.message);
        }
        //this.getUserTaskList();
      });
    },
    getTargetSize(size) {
      this.queryTargetTeamInfo.pageSize = size;
      this.getTargetTeamList();
    },
    getTargetPage(page) {
      this.queryTargetTeamInfo.pageIndex = page;
      this.getTargetTeamList();
    },
    searchTargetTeam() {
      this.queryTargetTeamInfo.pageIndex = 1;
      this.getTargetTeamList();
    },
    setTeamQuestion(val) {
      if (!val) {
        return;
      }
      this.question = this.questionList.filter((question) => question.chaId == val)[0];
      this.formValidate.port = this.question.port;
      //this.formValidate.vmId = '';
      this.getAllVmlist();
    },
    setTeamGroup(val) {
      if (!val) {
        return;
      }
      this.group = this.accessGroupList.filter((group) => group.id == val)[0];
      this.formValidate.teamName = this.group.name;
      //this.formValidate.vmId = '';
      this.getAllVmlist();
    },
    handleReset(name) {
      this.$refs[name].resetFields();
      //    this.addTarget = false;
    },
    queryCtfQuestionList() {
      //查询ctf题列表-不分页--不需要环境
      let obj = {
        pageIndex: 1,
        pageSize: 2147483647,
        isNeedEnv: '0'
        //isNeedSubmitFlag:'1',
        //category:this.autoPro.ctfType.join(',')
      };
      let _this = this;
      queryCtfList(obj).then((data) => {
        if (data.code == 1) {
          _this.questionList = data.data.items.filter((ques) => ques.imageId) || data.data;
          if (_this.questionList.length == 0) {
            _this.$Message.warning('该工程下没有满足要求的虚拟机');
          }
        } else {
          _this.$Message.warning(data.message);
        }
      });
    }
  }
};
</script>

<style>
.drillsTable .ivu-poptip-body {
  text-align: left !important;
}
.scenesHeader {
  margin-bottom: 16px;
}
.drillTables {
  min-height: 300px;
}
.drillsTable.ivu-table-wrapper {
  overflow: inherit;
}
</style>
<style scoped>
.Titles {
  background: #eeeeee;
  margin: 16px auto;
  padding: 10px 0;
}
.targetHeader {
  /*padding: 10px;*/
  margin: 15px 0;
}
</style>
